package cn.caipengbo.db;

import cn.caipengbo.domain.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

/**
 *  Implement CRUD
 */
public class PersonDAO {
    @Test
    public void createPerson() {
        //加载Hibernate配置文件，创建SessionFactory
        Configuration configuration =  new Configuration();
        configuration.configure(); //配置文件名字要固定，放在classes路径下
        //configuration.configure(""); //加载指定位置、指定名字的配置文件
        SessionFactory sessionFactory =  configuration.buildSessionFactory();
        //打开Session
        Session session = sessionFactory.openSession();
        //开始事务
        Transaction transaction = session.beginTransaction();
        //创建对象，操作对象
        Person person = new Person();
        person.setName("测试添加");
        //保存对象
        session.save(person);
        //事务提交
        transaction.commit();
        //关闭session
        session.close();

    }
    @Test
    public void retrievePersonById() {
        Configuration configuration =  new Configuration();
        configuration.configure();
        SessionFactory sessionFactory =  configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();

        Person person = (Person) session.get(Person.class,1L);
        System.out.println(person.toString());
        session.close();
    }
    @Test
    public void updatePerson() {
        Configuration configuration =  new Configuration();
        configuration.configure();
        SessionFactory sessionFactory =  configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        //  根据id 查询出一个对象
        Person person = (Person) session.get(Person.class,1L);
        //修改该对象
        person.setName("test");
        //修改
        session.update(person);
        transaction.commit();
        session.close();
    }
    public void deletePerson(){
        Configuration configuration =  new Configuration();
        configuration.configure();
        SessionFactory sessionFactory =  configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        //  根据id 查询出对象
        Person person = (Person) session.get(Person.class,1L);
        //删除
        session.delete(person);
        transaction.commit();
        session.close();
    }
}
